﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Widgetsphere.Generator.Common.GeneratorFramework;
using Widgetsphere.Generator.Models;
using Widgetsphere.Generator.ProjectItemGenerators;

namespace Acme.GeneratorExtension.GenerateToDataTransfer
{
	/// <summary>
	/// This generator will generate the [EntityName]MetaData.generated.cs file. This file 
	/// contains a public partial class [EntityName]MetaData. This generated
	/// file will contain the core implementation of the [EntityName]MetaData. It will be 
	/// overwritten each time a generation occurs. It should not be extended by programmers.
	/// </summary>
	[GeneratorItemAttribute("MetaData Class", typeof(MetaDataInfoClassExtensionGenerator))]
	public class MetaDataInfoClassGenerator : BaseGenerator
	{
		#region Class Members
		private const string RELATIVE_OUTPUT_LOCATION = @"\MetaData\";
		#endregion

		#region Overrides
		public override int FileCount
		{
			get { return _model.Database.Tables.Count; }
		}

		public override void Generate()
		{
			//Walk through all the tables in the model. 
			//Generate classes for those that are specified to be generated.
			foreach (Table table in _model.Database.Tables.Where(x => x.Generated).OrderBy(x => x.Name))
			{
				//Construct the template class passing it the current model file and table
				MetaDataInfoClassTemplate template = new MetaDataInfoClassTemplate(_model, table);

				//Create a string that represents the project relative output location of the file (Ex: \MetaData\Customer.cs)
				string fullParentName = RELATIVE_OUTPUT_LOCATION + template.ParentItemName;

				//Publish the Project Item Generated event for the generation engine to handle
				ProjectItemGeneratedEventArgs eventArgs = 
					new ProjectItemGeneratedEventArgs(template.FileName, template.FileContent, ProjectName, fullParentName, this, true);

				OnProjectItemGenerated(this, eventArgs);
			}
			ProjectItemGenerationCompleteEventArgs gcEventArgs = new ProjectItemGenerationCompleteEventArgs(this);
			OnGenerationComplete(this, gcEventArgs);
		}

		protected override string ProjectName
		{
			get
			{
				ModelRoot modelRoot = ((ModelRoot)_model);
				return string.Format("{1}.{0}.DataTransfer", modelRoot.ProjectName, modelRoot.CompanyName);
			}
		}
		#endregion

	}
}
